package com.zhuchang.self_rpc.test.democoding.nettydubbo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.omg.SendingContext.RunTime;

import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author RenPu
 * @Date 2022/2/12 15:03
 * @Version 1.0
 * @Description:
 **/
public class NettyDubboClient {

    private NettyDubboClientHandler clientHandler;

    public static ExecutorService executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private int count=0;

    public Object getBean(final Class<?> serviceClass,final String providerName){

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serviceClass},
                (proxy,method,args)->{

                    System.out.println("(proxy,method,args) 进入了" +(++count)+"次.....");

                    if(clientHandler==null){
                        initClient();

                    }
                    clientHandler.setPara(providerName+args[0]);

                    return executorService.submit(clientHandler).get();
                });

    }

    private void initClient() {

        clientHandler=new NettyDubboClientHandler();

        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder())
                                .addLast(new StringDecoder())
                                .addLast(clientHandler);
                    }
                });

        try {
            bootstrap.connect(new InetSocketAddress("127.0.0.1",6868)).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


}
